#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
#include <errno.h> // 用于处理错误码

//开始播放
snd_pcm_t* play_open(const char* name,
                      snd_pcm_format_t format,
                      unsigned int channel,
                      unsigned int rate,
                      snd_pcm_uframes_t* period)
{
    snd_pcm_t *playback; // PCM设备句柄
    snd_pcm_hw_params_t *params; // PCM硬件参数
    int err; // 用于存储错误码
    int dir;

    // 打开PCM设备用于回放
    if ((err = snd_pcm_open(&playback, name, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
        fprintf(stderr, "Error opening PCM device %s: %s\n", name, snd_strerror(err));
        return NULL;
    }

    // 分配参数对象，并用默认值填充
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(playback, params);

    // 设置参数
    // 设置访问类型：交错模式
    if ((err = snd_pcm_hw_params_set_access(playback, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
        fprintf(stderr, "Error setting access: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }
    // 设置数据格式：16位小端
    if ((err = snd_pcm_hw_params_set_format(playback, params, format)) < 0) {
        fprintf(stderr, "Error setting format: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }
    // 设置声道数：立体声
    if ((err = snd_pcm_hw_params_set_channels(playback, params, channel)) < 0) {
        fprintf(stderr, "Error setting channels: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }
    // 设置采样率
    if ((err = snd_pcm_hw_params_set_rate_near(playback, params, &rate, &dir)) < 0) {
        fprintf(stderr, "Error setting rate: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }

    printf("sample rate: %d Hz\n", rate);

    //设置周期大小
    if ((err = snd_pcm_hw_params_set_period_size_near(playback, params, period, &dir)) < 0) {
        fprintf(stderr, "Error setting period size: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }

    // 设置硬件参数
    if ((err = snd_pcm_hw_params(playback, params)) < 0) {
        fprintf(stderr, "Error setting HW params: %s\n", snd_strerror(err));
        snd_pcm_close(playback);
        return NULL;
    }

    // 获取周期大小
    snd_pcm_hw_params_get_period_size(params, period, &dir);

    return playback;
}

//停止播放
void play_close(snd_pcm_t* playback)
{
    snd_pcm_drain(playback); // 排空PCM设备
    snd_pcm_close(playback); // 关闭PCM设备
}

#if 0
int main()
{
    snd_pcm_t *playback; // PCM设备句柄
    snd_pcm_uframes_t period = 999; // 每个周期的帧数
    char *buffer; // 缓冲区，用于存储从文件中读取的音频数据
    FILE *pcm_file; // 输出PCM文件
    int err; // 用于存储错误码

    playback = play_open("hw:0,0", SND_PCM_FORMAT_S16_LE, 2, 44100, &period);
    if (!playback)
    {
        return 1;
    }

    printf("period: %d frames\n", period);

    buffer = (char *) malloc(snd_pcm_frames_to_bytes(playback, period)); // 分配缓冲区
    if (!buffer) {
        perror("malloc");
        play_close(playback);
        return 1;
    }

    // 打开输出文件
    pcm_file = fopen("output.pcm", "rb");
    if (!pcm_file) {
        perror("Error opening output file");
        free(buffer); // 释放缓冲区
        play_close(playback); // 关闭PCM设备
        return 1;
    }

    // 录制数据
    printf("Playing... Press Ctrl+C to stop.\n");
    while (1) {
        size_t bytes = fread(buffer, 1, snd_pcm_frames_to_bytes(playback, period), pcm_file);
        if (bytes == 0)
        {
            if (ferror(pcm_file))
            {
                perror("fread");
                continue;
            }

            if (feof(pcm_file))
            {
                break;
            }
        }

        snd_pcm_sframes_t frames = snd_pcm_writei(playback, buffer, snd_pcm_bytes_to_frames(playback, bytes));
        if (frames < 0)
        {
            fprintf(stderr, "Error from write: %s\n", snd_strerror(frames));
            snd_pcm_recover(playback, frames, 0);
        }
    }

    // 清理资源
    free(buffer); // 释放缓冲区
    fclose(pcm_file); // 关闭文件
    play_close(playback);

    return 0;
}

#endif